#include "StdAfx.h"
#include "SearchManager.h"

//////////////////////////////////////////////////////////////////////////
std::string SearchManager::ProcessRequest(PartPtr i_part) const
{
   std::ostringstream result;
   result << "Looking for:" << i_part->ToString() << std::endl;

   AggregatorList aggr = m_searchEngine.GetAggregators(i_part->GetSignature());

   if (aggr.size() == 0)
   {
      result << "Nothing found" << std::endl;
      return result.str();
   }

   result << "Found " << aggr.size() << std::endl;

   for(AggregatorList::const_iterator it = aggr.begin(); it!= aggr.end();++it)
   {
      result << "-------------------------------------------------" << std::endl;
      result << (*it)->ToString();
   }
   return result.str();
}

//////////////////////////////////////////////////////////////////////////
void SearchManager::PrintRequest(PartPtr i_part, std::ofstream& i_out) const
{
   i_out << ProcessRequest(i_part);
}

//////////////////////////////////////////////////////////////////////////
AggregatorList SearchManager::Searcher::GetAggregators(const Signature& i_signature) const
{
   std::map<PartPtr, int> list;
   for(Signature::const_iterator it = i_signature.begin();it!= i_signature.end(); ++it)
   {
      const PartsList parts = m_data.GetParts(*it);
      for(PartsList::const_iterator partIt = parts.begin(); partIt !=  parts.end(); ++partIt)
      {
         list[(*partIt)]++;
      }
   }

   AggregatorList result;
   std::map<PartPtr, int>::const_iterator it = list.begin();
   for(; it != list.end() && result.size() < m_props.m_quantity; ++it)
   {
      AggregatorPtr aggr = it->first->GetAggregator();
      if(it->second >= m_props.m_precision && aggr.get()          
         && std::find(result.begin(), result.end(), aggr) == result.end() )
      {
         result.push_back(aggr);
      }
   }

   return result;
}